package com.xu.cloud.common.processor;

import com.xu.cloud.common.constant.CryptConstant;
import com.xu.cloud.common.util.CodecUtil;
import com.xu.cloud.common.util.SymmetricEncryptUtil;

import javax.crypto.SecretKey;

/**
 * @author xuguan
 * @since 2024/6/30
 */
public class DecryptionConfigurationPropertyHelper {
    public static String randomEncryptionKey() {
        final SecretKey secretKey = SymmetricEncryptUtil.generateKey(128, CryptConstant.AES_SYMMETRIC_ALGORITHM);
        final String encryptionKey = CodecUtil.base64EncodeString(secretKey.getEncoded());
        System.out.printf("请在环境变量或者配置文件中配置: %s=%s\n", CryptConstant.ENCRYPTION_KEY_PROPERTY_NAME, encryptionKey);
        return encryptionKey;
    }

    public static String encryptionProperty(String value, String encryptionKey) {
        final byte[] bytes = CodecUtil.base64Decode(encryptionKey);
        final SecretKey secretKey = SymmetricEncryptUtil.getKeyFromBytes(bytes, CryptConstant.AES_SYMMETRIC_ALGORITHM);
        return SymmetricEncryptUtil.encryptBase64(value, secretKey, CryptConstant.AES_SYMMETRIC_ALGORITHM);
    }

    public static String decryptionProperty(String encryptionValue, String encryptionKey) {
        final byte[] bytes = CodecUtil.base64Decode(encryptionKey);
        final SecretKey secretKey = SymmetricEncryptUtil.getKeyFromBytes(bytes, CryptConstant.AES_SYMMETRIC_ALGORITHM);
        return SymmetricEncryptUtil.decryptBase64(encryptionValue, secretKey, CryptConstant.AES_SYMMETRIC_ALGORITHM);
    }

    public static void main(String[] args) {
        String value = "value";
        final String encryptionKey = randomEncryptionKey();
        final String encryptionProperty = encryptionProperty(value, encryptionKey);
        System.out.println("encryptionProperty = " + encryptionProperty);
        final String decryptionProperty = decryptionProperty(encryptionProperty, encryptionKey);
        System.out.println("decryptionProperty = " + decryptionProperty);
    }
}
